/********************************************************************************
 * Project Name		[JavaEE_Web]
 * File Name     	[HttpFilter.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 支持Http协议的Filter
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public abstract class HttpFilter implements Filter {

	private FilterConfig filterConfig;

	public FilterConfig getFilterConfig() {
		return filterConfig;
	}

	/**
	 * 供子类实现的初始化方法<br/>
	 * 可以通过getFilterConfig()获取 FilterConfig对象
	 */
	public void init() {
	}

	/**
	 * 不建议子类直接覆盖<br/>
	 * 若直接覆盖, 将可能会导致filterConfig成员变量初始化失败<br/>
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		init();
	}

	/**
	 * 原生的doFilter方法<br/>
	 * 把ServletRequest转为了HttpServletRequest<br/>
	 * 把ServletResponse转为了HttpServletResponse<br/>
	 * 调用了doFilter(HttpServletRequest request, HttpServletResponse response,
	 * FilterChain filterChain)
	 * 
	 * 若编写Filter的过滤方法不建议直接重写该方法.<br/>
	 * 建议重写doFilter(HttpServletRequest request, HttpServletResponse response,
	 * FilterChain filterChain)方法<br/>
	 * 
	 * @param request
	 * @param response
	 * @param filterChain
	 * @throws IOException
	 * @throws ServletException
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		this.doFilter(httpRequest, httpResponse, filterChain);
	}

	/**
	 * 抽象方法, 为Http请求定制
	 * 
	 * @param request
	 * @param response
	 * @param filterChain
	 * @throws IOException
	 * @throws ServletException
	 */
	public abstract void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws IOException, ServletException;

	@Override
	public void destroy() {
	}
}
